package org.osite.xml.converter;

import org.osite.xml.AttributeConverter;
import org.osite.xml.ParseContext;
import org.osite.xml.XmlParseException;

public class EnumConverter implements AttributeConverter<Enum<?>> {

  private static String toEnumNotation(String value) {
    return value.replace('-', '_').toUpperCase();
  }

  @SuppressWarnings("unchecked")
  @Override
  public Enum<?> convert(Class<?> type, String value, ParseContext context)
      throws XmlParseException {
    try {
      return Enum.valueOf((Class<? extends Enum>) type, toEnumNotation(value));
    } catch (IllegalArgumentException e) {
      throw new XmlParseException(
          "invalid " + type.getName() + ": " + value, e);
    }
  }

}
